package com.xxx.demo.service;

import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.xxx.demo.domain.Ebook;
import com.xxx.demo.domain.EbookExample;
import com.xxx.demo.mapper.EbookMapper;
import com.xxx.demo.req.EbookQueryReq;
import com.xxx.demo.req.EbookSaveReq;
import com.xxx.demo.resp.EbookQueryResp;
import com.xxx.demo.resp.PageResp;
import com.xxx.demo.util.CopyUtil;
import com.xxx.demo.util.SnowFlake;
import org.springframework.stereotype.Service;
import org.springframework.util.ObjectUtils;

import javax.annotation.Resource;
import java.util.List;

@Service
public class EbookService {
    @Resource
    private EbookMapper ebookMapper;

    @Resource
    private SnowFlake snowFlake;

    public PageResp<EbookQueryResp> list(EbookQueryReq req) {
        EbookExample ebookExample = new EbookExample();
        EbookExample.Criteria criteria = ebookExample.createCriteria();
        if (!ObjectUtils.isEmpty(req.getName()))
            criteria.andNameLike("%" + req.getName() + "%");

        if (!ObjectUtils.isEmpty(req.getCategoryId2()))
            criteria.andCategory2IdEqualTo(req.getCategoryId2());

        PageHelper.startPage(req.getPage(), req.getSize());
        List<Ebook> ebookList = ebookMapper.selectByExample(ebookExample);

        PageInfo<Ebook> pageInfo = new PageInfo<>(ebookList);
         /*List<EbookResp> respList = new ArrayList<>();
       for (Ebook ebook : ebookList) {
         *//*EbookResp ebookResp = new EbookResp();
            BeanUtils.copyProperties(ebook, ebookResp);*//*
            respList.add(CopyUtil.copy(ebook, EbookResp.class));
        }*/
        List<EbookQueryResp> list = CopyUtil.copyList(ebookList, EbookQueryResp.class);

        PageResp<EbookQueryResp> pageResp = new PageResp<>();
        pageResp.setTotal(pageInfo.getTotal());
        pageResp.setList(list);
        return pageResp;
    }

    public void save(EbookSaveReq req) {
        Ebook ebook = CopyUtil.copy(req, Ebook.class);
        if (ObjectUtils.isEmpty(req.getId())) {//新增
            ebook.setId(snowFlake.nextId());
            ebookMapper.insert(ebook);
        } else {
            ebookMapper.updateByPrimaryKey(ebook);
        }
    }

    public void delete(Long id) {
        ebookMapper.deleteByPrimaryKey(id);
    }
}
